<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-order-container">
    <div :class="{'box-shadow': !showMobilePage}" :style="device==='mobile'?{paddingBottom: 0}:{paddingBottom: '40px'}" class="bg ">
      <ChangeOrder v-if="isChangeOrder" v-model="inputMode" />
      <CreateClient
        v-if="isClientInfo"
        ref="clientInfoRef"
        :edit-limt="editLimt"
        :is-change-order="isChangeOrder"
        :is-other-info-disabled="!isOtherInfo"
        :is-client-disabled="!isClientInfo"
        :disabled-tax-amount="disabledTaxAmount || disabledClient"
      />
      <CreateOrder
        ref="orderInfoRef"
        :is-edit="isEdit"
        :is-make-up-order="isMakeUpOrder"
        :edit-limt="editLimt"
        :is-change-order="isChangeOrder"
        :is-disabled-without-file="!isOtherInfo"
        :is-file-disabled="!isPublishInfo"
        :disabled-tax-amount="disabledTaxAmount || disabledClient"
        :disabled-platform-account="!!sealBillType"
        :is-traffic-master="isTrafficMaster"
        style="padding-top: 8px;"
        @orderTypeChange="orderTypeChange"
        @orderSourceChange="orderSourceChange"
      />
      <CreateResource
        ref="resourceInfoRef"
        :edit-limt="editLimt"
        :is-change-order="isChangeOrder"
        :is-disabled-without-file="!isOtherInfo"
        :is-file-disabled="!isPublishInfo"
        :order-num="detailInfo.orderInfo? detailInfo.orderInfo.orderId || '':''"
        :order-type="orderType"
        style="padding-top: 8px;"
        @plateformChange="plateformChange"
        @orderFormChange="orderFormChange"
        @trafficMasterChange="getIsTrafficMasterValue"
      />
      <CreatePublish
        ref="publishInfoRef"
        :edit-limt="editLimt"
        :order-id="orderId"
        :get-order-info="getOrderInfo"
        :is-change-order="isChangeOrder"
        :order-num="detailInfo.orderInfo ? detailInfo.orderInfo.orderId || '':''"
        :is-file-disabled="!isPublishInfo"
        :plateform-id="plateformId"
        :order-form="orderForm"
        :is-link-required="isLinkRequired"
        style="padding-top: 12px;margin-bottom: 30px;"
      />
      <div class="box-block" style="margin-top: 12px;">
        <costBreakdownComponent
          ref="costBreakdownRef"
          :is-create="!isEdit"
          :order-info="detailInfo ? detailInfo.orderInfo : {}"
          :sealing-disabled="firstsSealing"
          :order-id="orderId"
          :is-detail="false"
          :is-make-up-order="isMakeUpOrder"
          :is-edit-order="isEditOrder"
          :hide-all-operation="isChangeOrder"
          :is-order="true"
          :is-cost-info="isCostInfo"
          :cost-belong-type="0">
          <div v-if="isChangeOrder" slot="title-after" class="tip-img-container">
            <el-tooltip :open-delay="800" placement="top">
              <div slot="content">变更单无法对原订单成本进行编辑，若需调整请直接在原订单调整</div>
              <img :src="helpIcon" class="tip-img" alt="">
            </el-tooltip>
          </div>
        </costBreakdownComponent>
      </div>

      <div class="select-related-container" style="margin-top: 8px;">
        <div class="flex-center">
          <div><Title title="关联合同" /></div>
          <div v-if="isChangeOrder" slot="title-after">
            <el-tooltip :open-delay="800" placement="top" class="tip-img-container">
              <div slot="content">变更单无法对原订单合同进行编辑，若需调整请直接在原订单调整</div>
              <img :src="helpIcon" class="tip-img" alt="">
            </el-tooltip>
          </div>
        </div>
        <div style="margin-top: 17px;">
          <InvoiceAndContract
            ref="ContractSelect"
            :is-change-order="isChangeOrder"
            :is-disabled="!isOtherInfo"
            :type="1"
            :related-contract-style="{
              position: 'absolute',top: '-7px',right: '24px'
            }"
            show-empty />
        </div>
      </div>
      <div class="select-related-container" style="margin-top: 9px;">
        <div style="margin-top: 10px;">
          <InvoiceAndContract
            ref="InvoiceSelect"
            :is-change-order="isChangeOrder"
            :is-disabled="!isOtherInfo"
            :related-contract-style="{
              position: 'absolute',top: '-7px',right: '24px'
            }"
            :type="2"
            :hide-all-operation="true"
            show-invoice-amount-total
            title="关联发票"
            show-empty >
            <div v-if="isChangeOrder" slot="title-after">
              <el-tooltip :open-delay="800" placement="top" class="tip-img-container">
                <div slot="content">变更单无法对原订单发票进行编辑，若需调整请直接在原订单调整</div>
                <img :src="helpIcon" class="tip-img" alt="">
              </el-tooltip>
            </div>
          </InvoiceAndContract>
        </div>
      </div>
      <div class="select-related-container" style="margin-top: 9px;">
        <RelatedQueryOrder
          ref="relatedQueryOrderRef"
          :is-edit="isEdit"
          :related-style="{
            position: 'absolute',top: '-7px',right: '24px'
          }"
          :tip-text="'每个订单仅能关联一笔询单'"
        />
      </div>
    </div>
    <fixed-pagination>
      <div class="create-order-btn">
        <el-button v-if="(!isEdit && hasRouteAuth('crm:orderList:addDraft')) || (isEdit && detailInfo.orderStatus === 0 && hasRouteAuth('crm:orderList:addDraft'))" :loading="btnLoading" type="primary" class="plain-create-btn" size="small" @click="toSubmit(false)">保存草稿</el-button>
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">{{ isEdit || isMakeUpOrder?(detailInfo.orderStatus === 0?'提交订单': '保存订单'):'创建订单' }}</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
    <Dialog
      ref="publishDialogRef"
      :btn1="'确认创建'"
      :btn2="'取消'"
      :requestDept="true"
      :summary="dialogSummary"
      :title="dialogTitle"
      tip="接收人请选择需要执行订单发布的人员"
      @handelOK="dialogFun" />
    <limitTable ref="limitTable" />
  </div>
</template>

<script>
import ChangeOrder from '@/components/CreateOrder/changeOrder';
import CreateClient from '@/components/CreateOrder/createClient';
import CreateOrder from '@/components/CreateOrder/createOrderEx';
import CreateResource from '@/components/CreateOrder/createResource';
import CreatePublish from '@/components/CreateOrder/createPublish';
import costBreakdownComponent from '@/components/CreateOrder/costList';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import RelatedQueryOrder from '@/components/RelatedQueryOrder';
import Title from '@/components/Title';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
import { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { addOrder, editOrder, getOrderInfo, linkRequiredCheck } from '@/api/order';
import helpIcon from '@/assets/orderlist/help.png';
import { mapState } from 'vuex';
import mobileCreate from '@/mixins/mobileCreate';
import limitTable from '../model/limitTable';

export default {
  components: { Dialog, Title, CreateClient, CreateOrder, ChangeOrder,
    CreateResource, CreatePublish, costBreakdownComponent, InvoiceAndContract, limitTable, RelatedQueryOrder },
  mixins: [mobileCreate],
  data() {
    const createOrder = this.createOrder;
    return {
      helpIcon,
      inputMode: 0, // 填写模式 0:填写实际值 1:填写补差值
      createOrderType: '', // createOrderType订单类型 change: 变更单
      btnLoading: false,
      isEdit: false,
      isMakeUp: false,
      disabledTaxAmount: false,
      sealBillType: null,
      orderId: null,
      sealingId: null,
      activeStepId: null,
      orderType: '',
      detailInfo: {},
      dialogSummary: '',
      dialogTitle: '',
      sealingDisabled: false,
      dialogFun: createOrder,
      firstsSealing: false,
      disabledClient: false,
      isLinkRequired: false,
      plateformId: null, // 监听下单平台选择
      orderForm: '', // 监听下单形式选择
      isTrafficMaster: false // 下单形式是否为流量主
    };
  },
  computed: {
    ...mapState({
      'opened': state => state.app.sidebar.opened,
      'device': state => state.app.device
    }),
    // 权限规则
    /**
      - 客户信息查看/编辑：勾选状态下，可 查看/编辑 订单用户信息(含列表、详情)
      - 发布信息编辑：勾选状态下，可 编辑 下单链接/上传文件信息：
      - 成本信息编辑：勾选状态下，可 编辑 除微任务成本/ID外的成本信息
      - 其他信息编辑：勾选状态下，可 编辑 除客户、发布、成本外的信息
    */
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    },
    isPublishInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:publishInfo');
    },
    isCostInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:costInfo');
    },
    isOtherInfo() {
      return this.isDraftEdit || hasRouteAuth('crm:orderList:otherInfo');
    },
    isDraftEdit() {
      // 在新建、编辑草稿状态时，如果拥有“新建草稿”的权限，则所有信息可以编辑
      return (!this.isEdit || (this.isEdit && this.detailInfo.orderStatus === 0)) && hasRouteAuth('crm:orderList:addDraft');
    },
    isMakeUpOrder() {
      // 补差单
      return Number(this.$route.query.orderType) === 7;
    },
    isChangeOrder() { // 变更单
      return this.createOrderType === 'change';
    },
    isEditOrder() { // 是否调整单
      return !!this.sealBillType;
    },
    editLimt() {
      /**
       * 编辑限制
       * 结算状态为已结算或审批已通过的无法编辑这些字段
       * 下单日期，刊例价，刊例价，含税金额，账号，下单平台，下单形式，主题，文案内容，下单链接，客户信息
       */
      // settlementStatus  0：待结算，1：已结算，2：结算中
      // settlementAuditState  0:待审批  1:通过审批  2:驳回
      if (this.detailInfo && !this.isChangeOrder) {
        return this.detailInfo.settlementStatus === 1 || this.detailInfo.settlementAuditState === 1;
      }
      return false;
    }
  },
  beforeRouteEnter(to, from, next) {
    if (to.query.draft) {
      to.meta.title = '编辑草稿订单';
    } else if (to.name === 'editOrder') {
      to.meta.title = to.query.createOrderType === 'change' ? '新增订单页' : '编辑订单页';
    }
    next();
  },
  mounted() {
    // createOrderType订单类型 change: 变更单
    this.createOrderType = this.$route.query.createOrderType || '';

    this.orderId = Number(this.$route.params.orderId) || '';
    this.sealBillType = Number(this.$route.query.sealBillType) || null; // 是否调整单，封账状态
    // 财务初审跳到编辑页时
    this.sealingId = Number(this.$route.query.sealingId) || null;
    // 这里控制从销售初审进入编辑页的编辑权限，2020-10-23删除，（客户名称、客户联系人、销售、策划执行人、刊例价、含税金额）
    this.firstsSealing = Boolean(this.sealingId); // v2.8新增 用于判断如果是从销售初审的入口进去的话，成本明细允许进行编辑,删除，关联
    this.activeStepId = Number(this.$route.query.activeStepId) || null;
    if (this.orderId) {
      this.isEdit = true;
      this.getOrderDetail();
    } else {
      this.isEdit = false;
    }
  },
  methods: {
    hasRouteAuth,
    getOrderDetail() {
      getOrderInfo(this.orderId).then(({ data }) => {
        this.detailInfo = data;
        if (data.orderInfo.orderPlatformId) {
          this.plateformId = data.orderInfo.orderPlatformId;
        }
        if (data.orderInfo.orderForm) {
          this.orderForm = data.orderInfo.orderForm;
        }
        this.detailInfo.orderInfo.priceTable = [{
          name: '含税',
          planPrice: data.orderInfo.planPrice === null ? '' : (data.orderInfo.planPrice / 100).toFixed(2),
          channelPrice: data.orderInfo.channelPrice === null ? '' : (data.orderInfo.channelPrice / 100).toFixed(2),
          totalPrice: data.orderInfo.taxAmount === null ? '' : (data.orderInfo.taxAmount / 100).toFixed(2),
          disabled: false
        }, {
          name: '刊例',
          planPrice: data.orderInfo.articlesPlanPrice === null ? '' : (data.orderInfo.articlesPlanPrice / 100).toFixed(2),
          channelPrice: data.orderInfo.articlesChannelPrice === null ? '' : (data.orderInfo.articlesChannelPrice / 100).toFixed(2),
          totalPrice: data.orderInfo.articlesPrice === null ? '' : (data.orderInfo.articlesPrice / 100).toFixed(2),
          disabled: false
        }, {
          name: '折扣',
          planPrice: data.orderInfo.planDiscountPrice === null ? '' : data.orderInfo.planDiscountPrice,
          channelPrice: data.orderInfo.channelDiscountPrice === null ? '' : data.orderInfo.channelDiscountPrice,
          totalPrice: data.orderInfo.discountPrice === null ? '' : data.orderInfo.discountPrice,
          disabled: true
        }];
        if (!this.isChangeOrder && (data.orderInfo.accountState === 1 || data.orderInfo.accountState === 2 || data.orderInfo.accountState === 3)) {
          // 0:待核销，1：已完成，2：部分核销，3：异常核销 默认为0 补差单状态不限制
          this.disabledTaxAmount = true;
        }

        // clientSettlementStatus 0: '未结算',1: '待提交',2: '待审批',3: '待上传',4: '待封存',5: '已完成'
        // 客户结算为未结算或待提交才可以编辑金额和客户
        if (data.clientInfo.clientSettlementStatus !== 0 && data.clientInfo.clientSettlementStatus !== 1) {
          this.disabledClient = true;
        }
        // 补差单和调整单要把成本列表的id和成本编号制空
        // if (this.isMakeUpOrder || this.isEditOrder) {
        //   if (data.costBreakdown && data.costBreakdown.costList) {
        //     data.costBreakdown.costList.forEach(i => {
        //       if (this.isMakeUpOrder && (i.costType !== 5 || (i.costType === 5 && !i.autoCost))) { // 补差单把含税成本设置为
        //         i.taxCost = 0;
        //       }
        //       // i.id = ''; // 不能在这里清除
        //       i.costNum = '';
        //       i.approvalStatus = 0; // 审批状态
        //       i.settlementStatus = 0; // 结算状态
        //     });
        //   }
        //   data.orderInfo.cost = null;
        // }
        // if (this.isMakeUpOrder) {
        //   data.orderInfo.taxAmount = null;
        //   data.orderInfo.channelPrice = null;
        //   data.orderInfo.discountPrice = null;
        //   data.orderInfo.priceBase = null;
        //   data.orderInfo.planPrice = null;
        //   data.orderInfo.articlesPrice = null;
        //   data.orderInfo.orderType = 7;
        // }
        if (this.$refs.clientInfoRef) this.$refs.clientInfoRef.insertDetail(data);
        if (this.$refs.orderInfoRef) {
          this.$refs.orderInfoRef.insertDetail(data);
          // this.$refs.orderInfoRef.$refs['formRef'].clearValidate('articlesPrice');
        }
        if (this.$refs.resourceInfoRef) this.$refs.resourceInfoRef.insertDetail(data);
        if (this.$refs.publishInfoRef) this.$refs.publishInfoRef.insertDetail(data);

        if (this.$refs.costBreakdownRef) this.$refs.costBreakdownRef.insertDetail(data.costBreakdown);
        // if (this.$refs.discountInfoRef) this.$refs.discountInfoRef.insertDetail(data);
        if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(data.contract);
        if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(data.invoiceInfo);
        if (this.$refs.relatedQueryOrderRef) this.$refs.relatedQueryOrderRef.setDefault(data.queryOrderInfo);
        if (data.orderInfo.orderPlatformId && data.orderInfo.orderFormId) {
          this.handleCheckLinkrequired(data.orderInfo.orderFormId);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    plateformChange(plateformId) {
      this.plateformId = plateformId;
    },
    orderSourceChange(val) {
      if (val === 2) {
        this.isLinkRequired = false;
      } else {
        const { orderFormId } = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
        orderFormId && this.handleCheckLinkrequired(orderFormId);
      }
    },
    orderFormChange(orderForm) {
      this.orderForm = orderForm.value;
      this.handleCheckLinkrequired(orderForm.id);
    },
    handleCheckLinkrequired(orderFormId) {
      const params = {
        orderFormId,
        orderPlatformId: this.plateformId
      };
      const orderSource = this.$refs.orderInfoRef && this.$refs.orderInfoRef.paramsObj.orderSource;
      linkRequiredCheck(params).then(res => {
        if (res.code === 200) {
          this.isLinkRequired = orderSource === 2 ? false : res.data.isRequired;
        }
      }).catch(err => console.error(err));
    },
    // 获取全部参数
    getTotalParams(isValidate = true) {
      const clientSubParams = this.$refs.clientInfoRef ? this.$refs.clientInfoRef.getParams() : {};
      const marketParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().clientInfo : {};
      const clientParams = Object.assign(clientSubParams, marketParams);
      // 订单信息
      const orderInfoRefParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().orderInfo : {};
      // 资源信息
      const resourceInfoParams = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
      // 发布信息
      const publishInfoParams = this.$refs.publishInfoRef ? this.$refs.publishInfoRef.getParams() : {};
      const orderParams = Object.assign(orderInfoRefParams, resourceInfoParams);
      // 成本信息
      const discountInfoParams = this.$refs.costBreakdownRef ? JSON.parse(JSON.stringify(this.$refs.costBreakdownRef.list)) : {};
      // 询单信息
      const queryOrderInfo = this.$refs.relatedQueryOrderRef ? this.$refs.relatedQueryOrderRef.getParams() : {};
      // 调整单和补差单要把id清除
      if ((this.isMakeUpOrder || this.isEditOrder) && discountInfoParams && discountInfoParams.costList) {
        discountInfoParams.costList.forEach(res => {
          res.id = '';
        });
      }
      const params = {
        saveDraft: !isValidate,
        orderInfo: orderParams,
        clientInfo: clientParams,
        costBreakdown: discountInfoParams,
        publishInfo: publishInfoParams,
        queryOrderInfo
      };
      if (queryOrderInfo.id) {
        params.queryOrderId = queryOrderInfo.id;
      }
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      return params;
    },
    // 获取全部validate
    getvalidatePromise(isValidate = true) {
      const validatePromise = [];
      if (this.$refs.clientInfoRef) validatePromise.push(this.$refs.clientInfoRef.validateForm(isValidate));
      if (this.$refs.orderInfoRef) validatePromise.push(this.$refs.orderInfoRef.validateForm(isValidate));
      if (this.$refs.publishInfoRef) validatePromise.push(this.$refs.publishInfoRef.validateForm(isValidate));
      if (this.$refs.resourceInfoRef) validatePromise.push(this.$refs.resourceInfoRef.validateForm(isValidate));
      if (this.$refs.orderInfoRef.$refs['priceTableRef'] && isValidate) validatePromise.push(this.$refs.orderInfoRef.$refs['priceTableRef'].validate(isValidate));
      return validatePromise;
    },
    toSubmit(isValidate = true) {
      try {
        const params = this.getTotalParams(isValidate);
        const validatePromise = this.getvalidatePromise(isValidate);
        // 编辑待审批订单时需要判断下单链接和附件
        if (this.isEdit && this.detailInfo && this.detailInfo.orderStatus >= 3 && !this.isChangeOrder) {
          if (this.isLinkRequired && !params.publishInfo.publishUrl) {
            ElMessage.error('请填写发布链接');
            return;
          }
          if (this.isLinkRequired && !params.publishInfo.autoPick && (!params.publishInfo.publishRemark || !params.publishInfo.attachment || params.publishInfo.attachment.length === 0)) {
            ElMessage.error('请填写发布文案和发布截图');
            return;
          }
        }
        if (!this.isEdit && !params.saveDraft && !this.isClientInfo) {
          ElMessage.warning('无客户信息编辑权限，无法创建订单');
          return false;
        }
        // 保存为草稿时，不验证必填项，但是销售和订单类型必须填写
        if (!isValidate && (!params.clientInfo.marketId || (!params.orderInfo.orderType && params.orderInfo.orderType !== 0))) {
          ElMessage.warning('请选择销售和订单类型');
          return false;
        }
        if (params.orderInfo.orderKind && params.orderInfo.orderKind.length > 5) { // 传值判断订单分类超过五个不允许保存成功
          ElMessage.warning('订单分类不允许超过5个，请重新选择');
          return false;
        }
        let defaultUser = [];
        if (params.saveDraft) {
          defaultUser.push({ id: params.clientInfo.marketId, userName: params.clientInfo.market });
        } else if (params.orderInfo && params.orderInfo.orderOperator) {
          defaultUser = params.orderInfo.orderOperator;
        }
        params.inputMode = this.inputMode;
        this.dialogSummary = params.saveDraft ? '请确认是否创建草稿订单' : '请确认是否创建订单';
        this.dialogTitle = params.saveDraft ? '订单创建草稿确认' : '订单创建确认';
        const dingTalkMsg = params.saveDraft ? '您有新待创建订单需要处理' : '您有新待发布订单需要处理';

        Promise.all(validatePromise).then(async(res) => {
        // 当运营模式=飞博主体，则不允许选择收入类型【媒介投放】
        // 当运营模式=非飞博主体，则不允许选择收入类型【媒体投放】
          if (params.orderInfo.operateModeParent && params.orderInfo.incomeTypeName) {
            if (params.orderInfo.operateModeParent === '飞博主体' && params.orderInfo.incomeTypeName === '媒介投放') {
              ElMessage.error('飞博主体收入类型不可选择媒介投放');
              return;
            }
            if (params.orderInfo.operateModeParent === '非飞博主体' && params.orderInfo.incomeTypeName === '媒体投放') {
              ElMessage.error('非飞博主体收入类型不可选择媒体投放');
              return;
            }
          }

          // 编辑变更单 orderType:8 时，判断客户名称是否变更
          if ((this.isEdit || this.isChangeOrder) && params.orderInfo.orderType === 8) {
            let handelOk = true;
            if (params.clientInfo.clientId !== this.detailInfo.clientInfo.clientId) {
              handelOk = await this.confirmMsg('当前变更修改了客户名称<br />将自动生成对冲单，对冲原订单客户收入金额');
            }
            if (!handelOk) return;
          }
          // 变更单走新建接口
          if (!this.isEdit || this.sealBillType || this.isMakeUpOrder || this.isChangeOrder) {
            this.dialogFun = this.createOrder;
            if (this.sealBillType || this.isMakeUpOrder || this.isChangeOrder) params.orderInfo.configureId = this.orderId;
            const historyOrderList = this.detailInfo.historyOrderList;
            if (historyOrderList && historyOrderList.length) {
              const configureIdItem = historyOrderList.find(i => i.orderType === 0 || i.orderType === 4);
              if (configureIdItem) params.orderInfo.configureId = configureIdItem.id;
            }

            if (this.isChangeOrder) {
              this.createOrder(params);
              return;
            }
            // 创建订单时需要确认框
            this.$refs.publishDialogRef.showDialog({ defaultMsg: dingTalkMsg, defaultObjectUser: defaultUser, extendParams: params });
          } else {
            if (this.detailInfo.orderStatus === 0 && !params.saveDraft) {
              this.dialogFun = this.editOrder;
              this.$refs.publishDialogRef.showDialog({ defaultMsg: '您有新待发布订单需要处理', defaultObjectUser: defaultUser, extendParams: params });
            } else {
              this.editOrder(params);
            }
          }
        }).catch((err) => {
          console.error(err);
          ElMessage.warning('请检查信息是否填写完整');
        });
      } catch (error) {
        console.log(error);
      }
    },
    editOrder(params) {
      params.url = `${location.origin}?redirect=/orderPage/orderdetail/${this.orderId}`;
      this.btnLoading = true;
      editOrder(this.orderId, params).then((res) => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.editAfter();
        } else if (res.code === 501) {
          // 501:销售额度不足
          this.$refs.limitTable.initData(0, res.data);
          return;
        } else {
          this.$message.error(res.message);
        }
      }, err => {
        console.log(err);
        this.btnLoading = false;
        if (err.code === 502) {
          // 502:客户额度不足
          this.$refs.limitTable.initData(1, err.data);
          return;
        }
      });
    },
    editAfter() {
      ElMessage.success('修改成功');
      // 判断是否从销售初审跳转过来的
      if (!this.sealingId) {
        this.$router.push({
          name: 'orderDetail',
          params: { orderId: this.orderId }
        });
      } else {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: this.sealingId }
        });
      }
    },
    createOrder(params) {
      params.url = `${location.origin}?redirect=/orderPage/orderdetail/`;
      this.btnLoading = true;
      // 如果是调整订单或者补差订单需要去除成本列表的id
      // if (this.sealBillType || this.isMakeUpOrder) {
      //   if (params.costBreakdown && params.costBreakdown.costList && params.costBreakdown.costList.length) {
      //     params.costBreakdown.costList.forEach(i => {
      //       i.id = 0;
      //     });
      //   }
      // }
      addOrder(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('添加成功');
          const orderType = params.orderInfo.orderType;
          if (orderType === 8 && res.data) {
            this.$router.push({
              name: 'orderDetail',
              params: { orderId: res.data }
            });
          } else {
            this.$router.push({
              name: 'allOrder'
            });
          }
        } else if (res.code === 501) {
          // 501:销售额度不足
          this.$refs.limitTable.initData(0, res.data);
          return;
        } else {
          this.$message.error(res.message);
        }
      }, err => {
        if (err.message && /未设置等级/g.test(err.message)) {
          showModal(err.message, '', { confirmButtonText: '前往设置' }).then(_ => {
            const id = params.clientInfo.clientId;
            const routerData = {
              name: 'detailCustomer',
              params: { customerId: id }
            };
            const url = this.$router.resolve(routerData);
            window.open(url.href, '_blank');
          }).catch(_ => {});
        }
        this.btnLoading = false;
        if (err.code === 502) {
          // 502:客户额度不足
          this.$refs.limitTable.initData(1, err.data);
          return;
        }
      });
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    getIsTrafficMasterValue(status) {
      this.isTrafficMaster = status;
    },
    orderTypeChange(orderType) {
      this.orderType = orderType;
    },
    toBack() {
      if (!this.sealingId) {
        this.$router.push({
          name: 'allOrder'
        });
      } else {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: this.sealingId }
        });
      }
    },
    confirmMsg(msg) {
      return new Promise((resolve, reject) => {
        this.$confirm(msg, '', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
          type: 'warning',
          showClose: false,
          center: true,
          iconClass: 'charge-icon',
          customClass: 'del-message del-message-cancel'
        }).then(() => {
          resolve(true);
        }).catch(() => {
          resolve(false);
        });
      });
    },
    getOrderInfo() {
      const orderInfoRefParams = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
      const platformOption = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.orderPlatformOption : [];
      return {
        orderInfo: orderInfoRefParams,
        platformOption
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.select-related-container {
  background:#fff;
  padding: 0 24px 24px 24px;
  position: relative;
}
.create-order-container {
  margin: 16px;
  .box-shadow {
    box-shadow: 2px 4px 10px #DDE1EA;
  }
  .bg {
    background:#fff;
  }
  & ::v-deep {
    .el-form-item{
      margin-bottom: 24px;
    }
    .el-input__inner  {
      line-height: 16px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
}
.box-block {
  padding: 0px 24px 27px 24px;
  background-color: #fff;
}
.create-order-btn {
  display: flex;
  width: 100%;
  justify-content: center;
}
.tip-img-container {
  display: flex;
  margin-left: 5px;
  align-items: center;
}
.tip-img {
  width: 14px;
  cursor: pointer;
}
.tip {
  font-size: 13px;
  color: #999;
  margin-left: 10px;
}
.plain-create-btn {
  background: #fff !important;
  color: #406EFF !important;
  border-color: #406EFF !important;
  &:hover {
    background-color: #406EFF !important;
    color: #fff !important;
  }
}
</style>
